<?php
declare (strict_types = 1);
use think\Model;
namespace app\admin\model;
use app\admin\model\AdminMenuApi as AdminMenuApiModel;
use app\admin\service\auth as AuthService;
/**
 * 超管菜单列表模型
 */
class AdminMenu extends BaseModel
{
	// 定义表名
    protected $name = 'admin_menu';

    // 定义主键
    protected $pk = 'admin_menu_id';

    // 追加字段
    // protected $append = [''];
    
    /**
     * 获取菜单id
     * @param array $adminMenuIds ID集
     * @return array
     */
    public static function getMenuIds(array $adminMenuIds)
    {
        $hidden = ['sort','create_time','update_time'];
        return (new self)->where('admin_menu_id', 'in', $adminMenuIds)->hidden($hidden)->select();
    }

    /**
     * [获取当前用户菜单权限]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function userMenuAuth($info)
    {
        $Auth = AuthService::getInstance();
        $menus = $Auth->getAdminMenu($info['admin_user_id']);
        return $menus;
    }
    /**
     * [addApi 新增]
     * Author：上官钧墨
     * @param [type] $data [description]
     */
    public function addMenu($data=[])
    {
    	$data['create_time'] = time();
    	$data['update_time'] = time();
    	return $this->insert($data);
    }
    /**
     * [editMenu 编辑]
     * Author：上官钧墨
     * @param  [type] $data [更新数据]
     */
    public function editMenu(array $data=[])
    {
        $data['update_time'] = time();
        return $this->save($data);
    }
    /**
     * [delMenu 删除菜单]
     * Author：上官钧墨
     */
    public function delMenu()
    {
        $menuApiModel = new AdminMenuApiModel;
        $detail = $menuApiModel->where(['admin_menu_id'=>$this->admin_menu_id])->select();
        if (count($detail)>0) {
            $this->error = '删除失败，该记录下有权限未取消';
            return false;
        }
        $find = $this->detail(['pid'=>$this->admin_menu_id]);
        if ($find) {
            $this->error = '删除失败，该记录下有关联菜单或权限';
            return false;
        }
        return $this->delete();
    }
    /**
     * [assignAuth 分配权限的接口]
     * Author：上官钧墨
     * @param  [type] $data [更新数据]
     */
    public function assignAuth(array $data=[])
    {
        $arr = [];
        foreach ($data['apiIds'] as $key => $admin_api_id) {
            array_push($arr,[
                'admin_menu_id'=>$data['admin_menu_id'],
                'admin_api_id'=>$admin_api_id,
                'create_time'=>time()
            ]);
        }

        // 思路：先删除原有的关系，再新增关系
        $menuApiModel = new AdminMenuApiModel;
        $menuApiModel->startTrans();
        $detail = $menuApiModel->where(['admin_menu_id'=>$data['admin_menu_id']])->select();
        if (count($detail)>0) {
            $resDel = $detail->delete();
            if (!$resDel) {
                $menuApiModel->rollback();
                $this->error = '分配失败，原关系清除失败';
                return false;
            }
        }
        if (!$arr) {
            $menuApiModel->commit();
            return true;
        }
        $res = $menuApiModel->insertAll($arr);
        if (!$res) {
            $menuApiModel->rollback();
            $this->error = '分配失败，请重试';
            return false;
        }
        $menuApiModel->commit();
        return true;
    }
    /**
     * [detail 获取详情]
     * Author：上官钧墨
     * @param  [type] $where [条件]
     */
    public function detail($where=[], $with = [],$hidden = [])
    {
        is_array($where) ? $filter = $where : $filter[$this->pk] = (int)$where;
        return $this->get($filter, $with,$hidden);
    }
    /**
     * [getList 获取菜单树]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function getList()
    {
        $menuApiModel = new AdminMenuApiModel;
        $allMenuApi = $menuApiModel->where([])->hidden(['create_time'])->select();

    	$hidden = ['create_time','update_time'];
    	$all = $this->where([])->hidden($hidden)->select();
    	$list = $this->children($all,$allMenuApi);
    	return $list;
    }
    /**
     * [allTree 获取菜单树-无需权限]
     * Author：上官钧墨
     * @return [type] [description]
     */
    public function allTree()
    {
        $menuApiModel = new AdminMenuApiModel;
        $allMenuApi = $menuApiModel->where([])->hidden(['create_time'])->select();

        $hidden = ['create_time','update_time'];
        $all = $this->where([])->hidden($hidden)->select();
        $list = $this->childrens($all,$allMenuApi);
        return $list;
    }
    /**
     * [children 生成菜单树-包含操作权限]
     * Author：上官钧墨
     * @param  array  $all [所有数据]
     * @param  integer $pid [上级admin_menu_id]
     */
    private function childrens($all,$allMenuApi,$pid = 0){
        $list = [];
        foreach ($all as $v) {
            if ($v['pid'] == $pid) {
                $item = $this->childrens($all,$allMenuApi,$v['admin_menu_id']);
                !empty($item) && $v['children'] = $item;
                $list[] = $v;
                unset($item);
            }
        }
        return $list;
    }
    /**
     * [children 生成菜单树]
     * Author：上官钧墨
     * @param  array  $all [所有数据]
     * @param  integer $pid [上级admin_menu_id]
     */
    private function children($all,$allMenuApi,$pid = 0){
    	$list = [];
    	foreach ($all as $v) {
	    	if (!$v['is_action']) {
	    		$v['authList'] = $this->authList($all,$allMenuApi,$v['admin_menu_id']);
                $v['apiIds'] = $this->apiIds($allMenuApi,$v['admin_menu_id']);
				if ($v['pid'] == $pid) {
	    			$item = $this->children($all,$allMenuApi,$v['admin_menu_id']);
	    			!empty($item) && $v['children'] = $item;
	    			$list[] = $v;
	    			unset($item);
	    		}
			}
    	}
    	return $list;
    }
    /**
     * [apiIds 获取已分配的接口id]
     * Author：上官钧墨
     * @param  [type] $list          [所有Api数据]
     * @param  [type] $admin_menu_id [菜单id]
     */
    private function apiIds($list,$admin_menu_id){
        $arr = [];
        foreach ($list as $k => $item) {
            if ($item['admin_menu_id'] == $admin_menu_id) {
                array_push($arr,$item['admin_api_id']);
            }
        }
        return $arr;
    }
    /**
     * [authList 获取本级操作权限列表]
     * Author：上官钧墨
     * @param  array $all           [所有数据]
     * @param  integer $admin_menu_id [本级admin_menu_id]
     */
    private function authList($all,$allMenuApi,$admin_menu_id){
    	$actionList = [];
    	foreach ($all as $key => $v) {
            $v['apiIds'] = $this->apiIds($allMenuApi,$v['admin_menu_id']);
    		if ($v['is_action'] && ($v['pid'] == $admin_menu_id)) {
				array_push($actionList, $v);
			}
    	}
    	return $actionList;
    }



}